import OSS from 'ali-oss'
const sha256 = require('hash.js/lib/hash/sha/256')

export const splitFileName = (text: any) => {
  // eslint-disable-next-line
  let pattern: any = /\.[^\.]+$/ // 正则
  let name = text // 名称
  let suffix = '' // 后缀
  if (pattern.exec(text) !== null) {
    name = text.slice(0, pattern.exec(text).index)
    suffix = text.slice(pattern.exec(text).index)
  }
  return {
    name,
    suffix
  }
}

// 生成 ossClient
export const createClient = (ossPolicy: any) => {
  return new OSS({
    accessKeyId: ossPolicy.accessKeyId,
    accessKeySecret: ossPolicy.accessKeySecret,
    stsToken: ossPolicy.securityToken,
    endpoint: ossPolicy.endpoint,
    bucket: ossPolicy.bucket
  })
}

// 上传Blob数据
export const ossUploadBlob = async (client: any, blob: any, path: any, options: any = {}) => {
  try {
    const uniqueid =
      sha256()
        .update(blob)
        .digest('hex') + Date.now()
    let { suffix } = splitFileName(blob.name)

    // console.log(suffix,0)
    if (options.suffix) {
      suffix = options.suffix
    }
    if (suffix.split('.').length === 1) {
      suffix = suffix + '.jpg'
    }
    console.log(suffix, 1, blob)
    const key = `${path}/${uniqueid}${suffix}`
    // console.log(key, '图片')
    const result = await client.multipartUpload(key, blob, { type: 'text/plain' })
    // console.log(result,'分片段成功了')
    return Promise.resolve(result.name)
  } catch (error) {
    // console.log(error,'分片段错误了')
    return Promise.reject(error)
  }
}
